﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using DNA.Utility;
using System.Web;

namespace DNA.Mvc
{
    public static class TemplateHelper
    {
        #region WebPageTemplate helpers

        public static WebPageTemplate LoadWebPageTemplate(Stream input)
        {
            using (var reader = new StreamReader(input))
            {
                string src = reader.ReadToEnd();
                reader.Close();
                return XmlSerializerUtility.DeserializeFromXmlText<WebPageTemplate>(src);
            }
        }

        public static void From(this WebPage page, WebPageTemplate template)
        {
            page.Title = template.Title;
            page.Description = template.Description;
            page.Keywords = template.Keywords;
            page.ImageUrl = template.ImageUrl;
            page.IconUrl = template.IconUrl;
            page.LinkUrl = template.LinkUrl;
            page.Target = template.Target;
            if (!page.IsShared)
                page.ViewData = template.Data;
            page.ViewName = template.Layout;
            page.AllowAnonymous = template.AllowAnonymous;
            page.ShowInMenu = template.ShowInMenu;

        }

        public static WebPageTemplate GetTemplate(this WebPage page)
        {
            var web = page.Web;
            var _pg = new WebPageTemplate()
            {
                Title = page.Title,
                Description = page.Description,
                Keywords=page.Keywords,
                ImageUrl=page.ImageUrl,
                IconUrl=page.IconUrl,
                LinkUrl = page.LinkUrl,
                Target = page.Target,
                Data = page.ViewData,
                Layout = page.ViewName,
                IsStatic = page.IsStatic,
                IsShared = page.IsShared,
                AllowAnonymous = page.AllowAnonymous,
                ShowInMenu = page.ShowInMenu,
                Path = page.Path
            };

           // if (web.Type == (int)WebTypes.Personal)
                _pg.Path = _pg.Path.ToLower().Replace("/" + web.Name.ToLower() + "/", "/{website}/");

            if (page.Widgets.Count> 0)
            {
                _pg.Widgets = new List<WidgetTemplate>();
                foreach (var widget in page.Widgets)
                {
                    if (!widget.IsStatic)
                        _pg.Widgets.Add(widget.GetTemplate());
                }
            }

            var children = web.WebPages.Where(p => p.ParentID == page.ID);
            if (children.Count() > 0)
            {
                _pg.Children = new List<WebPageTemplate>();
                foreach (var pc in children)
                    _pg.Children.Add(pc.GetTemplate());
            }
            return _pg;
        }

        public static string ToXml(this WebPage page)
        {
            return XmlSerializerUtility.SerializeToXml<WebPageTemplate>(page.GetTemplate());
        }

        #endregion

        #region WidgetTemplate helpers
        
        public static WidgetTemplate LoadWidgetTemplate(Stream input)
        {
            using (var reader = new StreamReader(input))
            {
                string src = reader.ReadToEnd();
                reader.Close();
                return XmlSerializerUtility.DeserializeFromXmlText<WidgetTemplate>(src);
            }
        }

        public static WidgetTemplate GetTemplate(this WidgetInstance widget)
        {
            if (widget.IsStatic)
                throw new FormatException("The static widget can not generate template");

            var descriptor = widget.WidgetDescriptor;
            var tmpl = descriptor.GetTemplate();
            tmpl.Defaults = new WidgetDefaults()
            {
                Title = widget.Title,
                TitleLinkUrl = widget.TitleLinkUrl,
                IconUrl = widget.IconUrl,
                ShowBorder = widget.ShowBorder,
                ShowHeader = widget.ShowHeader,
                HeaderCssText = widget.HeaderCssText,
                CssText = widget.CssText,
                BodyCssText = widget.BodyCssText,
                Action = descriptor.Action,
                ZoneID = widget.ZoneID,
                Position = widget.Pos,
                Controller = descriptor.Controller // widget.Controller,
            };
            
            tmpl.ID = descriptor.InstalledPath;

            var _preferences = widget.ReadUserPreferences();
            tmpl.UserPreferences = new List<WidgetUserPreference>();
            foreach (var key in _preferences.Keys)
            {
                tmpl.UserPreferences.Add(new WidgetUserPreference()
                {
                    Type = _preferences[key].GetType().ToString(),
                    Name = key,
                    Value = _preferences[key].ToString()
                });
            }
            return tmpl;
        }

        public static void From(this WidgetInstance widget, WidgetDescriptor descriptor)
        { 
            widget.Action = descriptor.Action;
            widget.Controller = descriptor.ControllerShortName;
            widget.Area = descriptor.Area;
            widget.ContentUrl = descriptor.ContentUrl;
            widget.IconUrl = descriptor.IconUrl;
            widget.Title = descriptor.Title;
            widget.IsClosable = descriptor.IsClosable.HasValue ? descriptor.IsClosable.Value : true;
            widget.IsDeletable = descriptor.IsDeletable.HasValue ? descriptor.IsDeletable.Value : true;
            widget.IsExpanded = true;
            widget.Scope = descriptor.Scopes;
            widget.ShowHeader = descriptor.ShowHeader.HasValue ? descriptor.ShowHeader.Value : true;
            widget.ShowBorder = descriptor.ShowBorder;
        }

        public static string ToXml(this WidgetInstance widget)
        {
            return XmlSerializerUtility.SerializeToXml<WidgetTemplate>(widget.GetTemplate());
        }

        #endregion

        #region WidgetDescriptior helpers

        public static WidgetTemplate GetTemplate(this WidgetDescriptor descriptor)
        {
            string fullPath = HttpContext.Current.Server.MapPath("~/content/widgets/") + descriptor.InstalledPath + "\\config.xml";
            var tmpl= XmlSerializerUtility.DeserializeFormXmlFile<WidgetTemplate>(fullPath);
            if (string.IsNullOrEmpty(tmpl.ID))
                tmpl.ID = descriptor.InstalledPath;
            return tmpl;
        }

        #endregion

        //#region WebTemplate helpers
        
        //public static WebTemplate GetTemplate(this Web web)
        //{
        //    //if (!HttpContext.Current.User.IsAdministrator())
        //    //    throw new UnauthorizedAccessException(Resources.language.AccessDenied_MSG);
        //    var template = new WebTemplate()
        //    {
        //        Title = web.Title,
        //        Description = web.Description,
        //        DefaultUrl = web.DefaultUrl,
        //        Language = web.DefaultLanguage,
        //        Copyright = web.Copyright,
        //        CssText = web.CssText,
        //        LogoImageUrl = web.LogoImageUrl,
        //        ShortcutIconUrl = web.ShortcutIconUrl,
        //        EnableUserRegistation = web.EnableUserRegistration,
        //        Theme = web.Theme,
        //        Type = (WebTypes)web.Type,
        //        MasterPage = web.MasterName,
        //        SearchKeywords = web.SearchKeywords
        //    };
            
        //    if (web.WebPages.Count>0)
        //    {
        //        template.WebPages = new List<WebPageTemplate>();
        //        var topLvPages = web.WebPages.Where(p => p.ParentID == 0).ToList();

        //        foreach (var page in topLvPages)
        //        {
        //            if ((page.IsStatic) && (!page.IsShared))
        //                continue;
        //            template.WebPages.Add(page.GetTemplate());
        //        }
        //    }
        //    return template;
        //}

        //public static string ToXml(this Web web)
        //{
        //    return XmlSerializerUtility.SerializeToXml<WebTemplate>(web.GetTemplate());
        //}
        //#endregion
    }
}
